package com.xq.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xq.entity.UmsUsers;
import com.xq.mapper.UserMapper;
import com.xq.entity.User;
import com.xq.security.token.SmsCodeAuthenticationToken;
import com.xq.service.IUmsUsersService;
import com.xq.service.SmsService;
import com.xq.service.AuthService;
import com.xq.vo.JsonVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl extends ServiceImpl<UserMapper, User> implements AuthService {

    @Autowired
    private IUmsUsersService iUmsUsersService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public JsonVO<String> getPasswordByUsername(String username) {
        return null;
    }

    /**
     * 这里是手机号验证码注册 注册成功后可以设置用户名和密码 如果不设置那么用户名和密码就为空 要使用用户和密码登录那自然也是不存再的
     * 1.需要设置用户名和密码的接口
     * 2.这里的验证码注册只需要手机号码和验证码
     * @param phone
     * @param code
     * @return
     */
    @Override
    public JsonVO<String> register(String phone,String code) {
        //发送验证码
        //smsService.sendVerificationCode(phone);
        boolean validated = smsService.validateCode(phone, code);
        if (!validated) {
            throw  new RuntimeException("验证码错误或已过期");
        }
        if (iUmsUsersService.getUserByPhone(phone)!=null) {
            throw  new RuntimeException("用户已存在");
        }
        iUmsUsersService.setPhone(phone);

        return JsonVO.success("注册成功");
    }

    /**
     * 为用户设置账户和密码
     * 设置密码是在手机号成功注册以后，所以还需要传入手机号码
     * @param username
     * @param password
     */
    @Override
    public JsonVO<String> setUserByUsername(String username, String password, String phone) {
        if (iUmsUsersService.getUserByPhone(username)!=null) {
            throw  new RuntimeException("用户已经存在");
        }

        UmsUsers user = new UmsUsers();
        user.setUsername(username);
        user.setPasswordHash(passwordEncoder.encode(password));
        user.setMobile(phone);
        int update = iUmsUsersService.setUserAndPassword(user);
        if (update<0) {
            throw  new RuntimeException("设置失败，请稍后重试");
        }
        return JsonVO.success("设置成功");
    }

    /**
     * 用户密码登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public JsonVO<String> loginByUsername(String username, String password) {

        try {
            //使用springSecurity进行用户登录验证
            // Authentication authentication = authenticationManager.authenticate(
            //         new UsernamePasswordAuthenticationToken(username, password));

            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            //验证成功才会有下一步认证信息的存储，若失败则会抛出异常
            //将认证信息存储到SecurityContext中
            //SecurityContextHolder.getContext().setAuthentication(authentication);
        }catch (Exception e) {
            throw  new RuntimeException("账号或者密码错误");
        }
        return JsonVO.success("登录成功");
    }

    /**
     * 根据手机号验证码登录
     * @param code
     * @return
     */
    @Override
    public JsonVO<String> loginByCode(String phone,String code) {
        try {
            Authentication authentication = new SmsCodeAuthenticationToken(phone, code);
            Authentication authenticated = authenticationManager.authenticate(authentication);
            SecurityContextHolder.getContext().setAuthentication(authenticated);
        }catch (Exception e) {
            throw new RuntimeException("登录失败");
        }
        return JsonVO.success("登录成功");
    }



}
